package selectClass.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import selectClass.Student;
import selectClass.Taco;
import selectClass.User;
import selectClass.data.StudentRepository;
import selectClass.data.UserRepository;

import javax.persistence.criteria.Order;
import javax.validation.Valid;
import java.io.*;
import java.security.Principal;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/studentInformation")
@SessionAttributes("taco")
public class studentInformationController {
    private StudentRepository studentRepository;

    private UserRepository userRepo;

    @Autowired
    public studentInformationController(StudentRepository studentRepository,UserRepository userRepo) {
        this.studentRepository = studentRepository;
        this.userRepo=userRepo;
    }

    @ModelAttribute(name = "taco")
    public Taco taco(){
        return new Taco();
    }

    @ModelAttribute(name = "student")
    public Student student(){return new Student();}

    @GetMapping("/current")
    public String studentInformation(Model model,@AuthenticationPrincipal User user,@ModelAttribute Student student,Principal principal) {
        String username = principal.getName();
        user = userRepo.findByUsername(username);
        model.addAttribute("user", user);


        if (student.getName() == null) {
            student.setName(user.getFullname());
        }
        if (student.getCollege() == null) {
            student.setCollege(user.getUserCollege());
        }
        if (student.getGrade() == null) {
            student.setGrade(user.getUserGrade());
        }
        student.getMajor();
        if (student.getMajor() == null) {
            student.setMajor(user.getUserMajor());
        }
        student.getMajor();



        return "studentInformation";
    }

    @PostMapping
    public String processOrder(@Valid Student student, Errors errors, @ModelAttribute Taco taco,
                               @AuthenticationPrincipal User user) {
        if (errors.hasErrors()) {
            return "studentInformation";
    }

        student.setUser(user);
        student.getStudentNumber();

        Student saved=studentRepository.save(student);
        taco.addDesign(saved);

        return "redirect:/design";
    }
}
